package de.melistik.smugmugsync.connect;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.activation.MimetypesFileTypeMap;

import com.kallasoft.smugmug.api.json.entity.Album;
import com.kallasoft.smugmug.api.json.entity.Image;
import com.kallasoft.smugmug.api.json.v1_2_1.APIVersionConstants;

public class RemoveDuplicates {

	Logger LOGGER = Logger.getLogger(RemoveDuplicates.class.getName());
	private SmugMugConnection connection;

	public RemoveDuplicates(SmugMugConnection connection) {
		this.connection = connection;
	}

	public List<File> removeDuplicates(List<File> fileList, Album album) {
		List<File> result = new ArrayList<File>();
		if (album != null) {
			try {
				// Get all of the images in the album
				com.kallasoft.smugmug.api.json.v1_2_1.images.Get imagesGet = new com.kallasoft.smugmug.api.json.v1_2_1.images.Get();
				com.kallasoft.smugmug.api.json.v1_2_1.images.Get.GetResponse images = imagesGet
						.execute(APIVersionConstants.SECURE_SERVER_URL,
								SmugMugConnection.API_KEY, connection
										.getResponse().getSessionID(), album
										.getID(), album.getAlbumKey(), true);

				// Reads out all existing files of Album
				List<Image> imageList = images.getImageList();

				// Fills MD5Set and FilenameSet to identify duplicate uploads
				Set<String> filesMD5Set = new HashSet<String>();
				Set<String> fileNames = new HashSet<String>();
				for (Image current : imageList) {
					filesMD5Set.add(current.getMD5Sum() != null ? current
							.getMD5Sum().toLowerCase() : null);
					fileNames.add(current.getFileName().toLowerCase());
				}

				// Calculate MD5SUM of each upload candidate and compare to
				// those in list
				String md5sum = null;
				for (File candidate : fileList) {
					System.out.print(".");
					if (new MimetypesFileTypeMap().getContentType(candidate)
							.contains("image")) {
						md5sum = org.apache.commons.codec.digest.DigestUtils
								.md5Hex(new FileInputStream(candidate));
						if (md5sum != null) {
							if (!filesMD5Set.contains(md5sum.toLowerCase()))
								result.add(candidate);
						} else {
							result.add(candidate);
						}
					} else {
						if (!fileNames.contains(candidate.getName()
								.toLowerCase()))
							result.add(candidate);
					}
				}
			} catch (IOException ex) {
				LOGGER.log(Level.SEVERE, null, ex);
			}
		} else {
			LOGGER.log(Level.SEVERE, "Album is null - not found?");
		}
		return result;
	}
}
